<template>
  <el-upload
    class="upload-demo"
    drag
    action
    :limit="1"
    :http-request="handleFileUpload"
    :before-upload="beforeFileUpload"
    :on-remove="handleRemove"
    :file-list="fileList"
    :on-exceed="handleExceed"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div
      class="el-upload__tip"
      slot="tip"
    >文件大小不能超过100M</div>
  </el-upload>
</template>

<script>
import { Message, Loading } from 'element-ui';
import { parseError } from '../utils';
import { v4 as uuid } from 'uuid';
import { uploadFileApi } from '../api/upload';
import { regularUrl } from '../utils/regular';

export default {
  model: {
    prop: 'fileUrl',
    event: 'update'
  },
  props: {
    fileUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    fileUrl: {
      handler(value) {
        if (!value) this.fileList = [];
      }
    }
  },
  methods: {
    handleFileUpload(option) {
      try {
        const [extension] = option.file.name.split('.').reverse();
        if (!extension) return Message.error('文件格式不正确');
        const loadingInstance = Loading.service({
          lock: true,
          text: '文件上传中，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const formData = new FormData();
        formData.append('file', option.file, encodeURIComponent(option.file.name));
        uploadFileApi(formData)
          .then(res => {
            this.$emit('update', res);
            this.$emit('file-size', option.file.size);
            this.$emit('file-name', option.file.name);
          })
          .catch(error => Message.error(parseError(error)))
          .finally(() => loadingInstance.close());
      } catch (error) {
        Message.error(parseError(error));
      }
    },
    beforeFileUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 100;
      if (!isLt10M) Message.error('文件大小不能超过100MB');

      return isLt10M;
    },
    handleRemove(file) {
      this.fileUrl = '';
      this.$emit('file-size', 0);
    },
    handleExceed(file, fileList) {
      Message.warning('只能上传一个文件');
    }
  }
};
</script>
